package ace.module.upms.core.impl.manager.impl;

import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.AbstractSpringDtoManager;
import ace.cmp.util.TreeUtils;
import ace.cmp.util.model.dto.TreeNode;
import ace.module.upms.api.constant.UpmsConstant;
import ace.module.upms.api.model.dto.UpmsMenuDto;
import ace.module.upms.core.impl.dao.entity.UpmsMenu;
import ace.module.upms.core.impl.manager.UpmsMenuManager;
import ace.module.upms.core.impl.manager.cache.UpmsMenuCacheManager;
import java.util.Comparator;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
* 菜单权限 spring data jdbc querydsl rsql manager implement.
*
* @author Caspar
*/
@Slf4j
@AllArgsConstructor
@Component
public class UpmsMenuManagerImpl
    extends AbstractSpringDtoManager<UpmsMenu, Long, UpmsMenuDto>
    implements UpmsMenuManager {
  private final UpmsMenuCacheManager upmsMenuCacheManager;

  @Override
  public List<UpmsMenu> getByUpmsAppIdAndDeleteFlagIsFalse(Long upmsAppId) {
    return upmsMenuCacheManager.getByUpmsAppIdAndDeleteFlagIsFalse(upmsAppId);
  }

  @Override
  public List<TreeNode<UpmsMenu>> getTreeByUpmsAppIdAndDeleteFlagIsFalse(Long upmsAppId) {
    List<UpmsMenu> menuList = upmsMenuCacheManager.getByUpmsAppIdAndDeleteFlagIsFalse(upmsAppId);
    List<TreeNode<UpmsMenu>> treeNodes =
        TreeUtils.buildTree(
            menuList,
            p -> p.getParentId() == null || p.getParentId().equals(UpmsConstant.ROOT_PARENT_ID),
            UpmsMenu::getId,
            p -> menuList.stream().filter(menu -> menu.getParentId().equals(p.getId())).toList());
    TreeUtils.traversalSort(treeNodes, Comparator.comparing(p -> p.getValue().getSort()));
    return treeNodes;
  }
}
